import { ref } from "vue";
import { getAiList, getSearchList } from "@/api/index";

export default function useAiSearch() {
  let pageAiParams = ref({
    loading: false,
    finished: false,
    error: false,
    page: 1,
    pageSize: 10,
    finishedText: "没有更多了",
  });
  let aiList = ref([]);
  let localParams = {};
  let url = getAiList; //默认是最新发布的接口
  const searchAiList = (data) => {
    if (data) {
      aiList.value = [];
      pageAiParams.value.page = 1;
      pageAiParams.value.finished = false;
      localParams = Object.assign(localParams, data);
      url = getSearchList;
    }
    let params = {
      area: localParams.area,
      edu: localParams.edu,
      xz: localParams.cxz,
      flag_type: 8,
      yuangong: localParams.yuangong,
      keywords: localParams.keywords,
      classid: localParams.classid,
      regionid: localParams.regionid,
      gznum: localParams.gznum,
      salary: localParams.salary,
      page: pageAiParams.value.page - 1,
      page_size: localParams.pageSize || pageAiParams.value.pageSize,
    };
    pageAiParams.value.loading = true;
    url(params)
      .then((res) => {
        if (res.code == 200) {
          // 修改这里 - 如果是第一页则替换，否则追加
          if (params.page === 0) {
            // 第一页
            aiList.value = res.data;
          } else {
            aiList.value.push(...res.data);
          }
          if (!res.data.length && pageAiParams.value.page == 1) {
            pageAiParams.value.finishedText = "很抱歉，未找到符合要求的信息！";
          } else {
            pageAiParams.value.finishedText = "没有更多了";
          }
          if (res.data.length < pageAiParams.value.pageSize) {
            pageAiParams.value.finished = true;
          }
          if (!pageAiParams.value.finished) {
            pageAiParams.value.page++;
          }
        } else {
          pageAiParams.value.error = true;
        }
        pageAiParams.value.loading = false;
      })
      .catch((err) => {
        pageAiParams.value.error = true;
        pageAiParams.value.loading = false;
      });
  };

  return {
    pageAiParams,
    aiList,
    searchAiList,
  };
}
